/*
 *  Copyright 2010 UPF Telecos 4th group G.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package edu.upf.listeners;

import edu.upf.core.ClientLogic;
import edu.upf.utils.Definitions;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smackx.filetransfer.FileTransferListener;
import org.jivesoftware.smackx.filetransfer.FileTransferRequest;
import org.jivesoftware.smackx.filetransfer.IncomingFileTransfer;

/**
 * Implements the listener logic when a media transfer petition message
 * is received
 * @author netjois
 */
public class MediaTransferListener implements FileTransferListener, Definitions {

    private String transferID;
    private ClientLogic clientLogic;

    /**
     * Constructor of the listener, received a client logic object for
     * callbacks and the transferID to accept the incoming transfer
     * @param clientLogic
     * @param transferID
     */
    public MediaTransferListener(ClientLogic clientLogic, String transferID){
        this.transferID=transferID;
        this.clientLogic=clientLogic;
    }

    /**
     * Method called when the request is received, decides if is has to be
     * accepted, stores the data and notifies the client logic
     * @param request
     */
    @Override
    public void fileTransferRequest(FileTransferRequest request) {
        // Check to see if the request should be accepted
        if (transferID.equals(request.getFileName())) {
            // Accept it
            IncomingFileTransfer transfer = request.accept();
            try {
                transfer.recieveFile(new File(NAME));
                 clientLogic.mediaReceived(request.getDescription());
            } catch (XMPPException ex) {
                Logger.getLogger(MediaTransferListener.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            // Reject it
            request.reject();
        }
    }
}
